/**
 * 
 */
package com.seraph.zys.web.pccexport;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.seraph.bi.suite.support.core.resources.LocalResourcesManager;
import com.seraph.bi.suite.support.security.BaseUser;
import com.seraph.bi.suite.support.security.LoginUtil;
import com.seraph.bi.suite.support.util.json.JsonUtils;
import com.seraph.bi.suite.support.web.base.BaseResponse;
import com.seraph.bi.suite.support.web.json.JsonBaseReportActionProviderController;
import com.seraph.zys.dao.ScOrgDAO;
import com.seraph.zys.dao.ViewAllFundsArrangementDAO;
import com.seraph.zys.dao.domain.ScOrg;
import com.seraph.zys.dao.domain.ViewAllFundsArrangement;
import com.seraph.zys.dao.domain.ViewAllFundsArrangementExample;
import com.seraph.zys.report.model.exp.ReportFunctionParser;
/**
 * 类说明:<br>
 * 创建时间: 2011-01-12<br>
 * @author <br>
 * @email:<br>
 */
@Controller
@RequestMapping("/viewAllFundsArrangementAction.do")
public class ViewAllFundsArrangementActionController extends JsonBaseReportActionProviderController {


	private static final Logger log = Logger.getLogger(ViewAllFundsArrangementActionController.class);
	
	private static String templateDir = "/template";

	private static String tmpDir = "/tmp";

	private static String templateName = ViewAllFundsArrangement.class
			.getSimpleName() + ".xlsx";	

	private String fiscalYear;

	private String fromArea;
	
	@Autowired
	private ReportFunctionParser reportFunctionParser;

	@Autowired
	private LocalResourcesManager localResourcesManager;	

	@Autowired
	private ScOrgDAO scOrgDAO;

	public void setScOrgDAO(ScOrgDAO scOrgDAO) {
		this.scOrgDAO = scOrgDAO;
	}		
	
	public void setLocalResourcesManager(LocalResourcesManager localResourcesManager) {
		this.localResourcesManager = localResourcesManager;
	}	
	
	public void setReportFunctionParser(
			ReportFunctionParser reportFunctionParser) {
		this.reportFunctionParser = reportFunctionParser;
	}	

	public String getFiscalYear() {
		if (fiscalYear == null || "".equals(fiscalYear)) {
			return String
					.valueOf(Calendar.getInstance().get(Calendar.YEAR) + 1);
		}

		return fiscalYear;
	}

	public void setFiscalYear(String fiscalYear) {
		this.fiscalYear = fiscalYear;
	}

	public String getFromArea() {
		if (fromArea == null || "".equals(fromArea)) {
			BaseUser user = (BaseUser) LoginUtil.getUser();
			return user.getOrgCode();
		}
		return fromArea;
	}

	public void setFromArea(String fromArea) {
		this.fromArea = fromArea;
	}
	
	@Autowired
	private ViewAllFundsArrangementDAO viewAllFundsArrangementDAO;

	public void setViewAllFundsArrangementDAO(ViewAllFundsArrangementDAO viewAllFundsArrangementDAO) {
		this.viewAllFundsArrangementDAO = viewAllFundsArrangementDAO;
	}

	/**
	 * 功能说明: 查询单条记录<br>
	 * 创建时间: 2011-1-12 <br>
	 * @author: 徐信信<br>
	 */
	public Object onRetrieve(String[] keyNames, Object entity) {		
		ViewAllFundsArrangement viewAllFundsArrangement=null;
/*
		try{		
		   		viewAllFundsArrangement= viewAllFundsArrangementDAO.selectByPrimaryKey(Integer.parseInt(BeanUtils.getProperty(entity, keyNames[0])));
		} catch(Exception e){
			Throwable t = e.getCause();
			if (t.getMessage() == null || "".endsWith(t.getMessage())) {
				t = t.getCause();
			}
			String message = "查询失败！异常信息：[" + t.getMessage() + "]";
			log.debug(message);
			return new BaseResponse(BaseResponse.FALSE, message);
		}*/
		return viewAllFundsArrangement;
	}

	/**
	 * 
	 */
	public Object onCreate(String[] keyNames, Object entity) {
		//添加信息
		BaseResponse baseResponse = null;
		try {
			ViewAllFundsArrangement viewAllFundsArrangement = (ViewAllFundsArrangement) entity;
			BaseUser user = (BaseUser) LoginUtil.getUser();
			String org_Code = user.getOrgCode();
			viewAllFundsArrangement.setFromArea(org_Code);				
		
			viewAllFundsArrangementDAO
					.insert((ViewAllFundsArrangement) reportFunctionParser
							.setFunctionValues(viewAllFundsArrangement));			
							
			baseResponse = new BaseResponse(BaseResponse.TRUE, "添加成功！");
		} catch (Exception e) {
			Throwable t = e.getCause();
			if (t.getMessage() == null || "".endsWith(t.getMessage())) {
				t = t.getCause();
			}
			String message = "操作失败！异常信息：[" + t.getMessage() + "]";
			log.debug(message);
			baseResponse = new BaseResponse(BaseResponse.FALSE, message);
		}
		return baseResponse;
	}

	/**
	 * 
	 */
	public Object onUpdate(String[] keyNames, Object entity) {

		//修改信息
		BaseResponse baseResponse = null;
/*		try {
			ViewAllFundsArrangement viewAllFundsArrangement = (ViewAllFundsArrangement) entity;
			BaseUser user = (BaseUser) LoginUtil.getUser();
			String org_Code = user.getOrgCode();
			viewAllFundsArrangement.setFromArea(org_Code);			
			if(viewAllFundsArrangement.getId_old()==null){
				viewAllFundsArrangement.setId_old(viewAllFundsArrangement.getId());
			}		
			viewAllFundsArrangementDAO.updateByPrimaryKeyForCgs((ViewAllFundsArrangement) reportFunctionParser
							.setFunctionValues(viewAllFundsArrangement));
			baseResponse = new BaseResponse(BaseResponse.TRUE, "修改成功！");
		} catch (Exception e) {
			Throwable t = e.getCause();
			if (t.getMessage() == null || "".endsWith(t.getMessage())) {
				t = t.getCause();
			}
			String message = "修改失败！异常信息：[" + t.getMessage() + "]";
			log.debug(message);
			baseResponse = new BaseResponse(BaseResponse.FALSE, message);
		}*/
		return baseResponse;
	}

	/**
	 * 
	 */
	public Object onDelete(String[] keyNames, Object entity) {

		BaseResponse baseResponse=null;
/*		try{		
		   		viewAllFundsArrangementDAO.deleteByPrimaryKey(Integer.parseInt(BeanUtils.getProperty(entity, keyNames[0])));
		   baseResponse = new BaseResponse(BaseResponse.TRUE, "删除成功！");						
		} catch(Exception e){
			Throwable t = e.getCause();
			if (t.getMessage() == null || "".endsWith(t.getMessage())) {
				t = t.getCause();
			}
			String message = "删除失败！异常信息：[" + t.getMessage() + "]";
			log.debug(message);
			baseResponse = new BaseResponse(BaseResponse.FALSE, message);	
		}*/
		return baseResponse;		
	}

	@Override
	public Object onDoExcel(HttpServletRequest request,
			HttpServletResponse response, Object entity) {

		ViewAllFundsArrangementExample example = new ViewAllFundsArrangementExample();		
		example.setFromArea(this.getFromArea());
		example.setFromArea_Indicator(ViewAllFundsArrangementExample.EXAMPLE_EQUALS);
		example.setFiscalYear(Integer.parseInt(this.getFiscalYear()));
		example.setFiscalYear_Indicator(ViewAllFundsArrangementExample.EXAMPLE_EQUALS);

		@SuppressWarnings("unchecked")
		Map<String, String> orgMap = localResourcesManager.getCodeInfoMapByType("SC_ORG_MAP");
		String orgName = orgMap.get(this.getFromArea());	
		ScOrg scOrg = scOrgDAO.selectByOrgCode(this.getFromArea());
		
		if(scOrg.getOrgLevel()==100){
			orgName="各省";
		}
		
		List<?> list = viewAllFundsArrangementDAO.selectByExample(example);
		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("ViewAllFundsArrangement", list);
		beans.put("FiscalYear", this.getFiscalYear());
		beans.put("OrgName", orgName);		
		XLSTransformer transformer = new XLSTransformer();
		transformer.markAsFixedSizeCollection("ViewAllFundsArrangement");

		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		FileInputStream fis = null;
		OutputStream fos = null;

		String templateFileName = this.getTemplateFileName(request);
		String destFileName = this.getDestFileName(request);
		String fileName = this.getFiscalYear()+"_"+this.getFromArea();

		response.reset();
		response.setContentType("application/vnd.ms-excel");
		try {
			File file=new File(destFileName);
			if(file.exists()){
				file.delete();
			}		
			transformer.transformXLS(templateFileName, beans, destFileName);
			response.addHeader("Content-Disposition", "attachment;filename="
					+ java.net.URLEncoder.encode(fileName, "utf-8") + ".xlsx");

			fos = response.getOutputStream();
			fis = new FileInputStream(destFileName);
			bos = new BufferedOutputStream(fos);
			bis = new BufferedInputStream(fis);

			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			bos.flush();
		} catch (ParsePropertyException e) {
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (bis != null) {
					bis.close();
				}
				if (fos != null) {
					fos.close();
				}
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	private String getTemplateFileName(HttpServletRequest request) {
		try {
			return request.getSession().getServletContext()
					.getResource(templateDir + File.separator + templateName)
					.getFile();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	private String getDestFileName(HttpServletRequest request) {
		try {
			return request.getSession().getServletContext().getResource(tmpDir)
					.getPath()
					+ File.separator + templateName;
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	@Override
	protected Object onBind(HttpServletRequest request,
			HttpServletResponse response) {
			
		this.setFiscalYear(request.getParameter("fiscalYear"));
		this.setFromArea(request.getParameter("fromArea"));		
		String record = request.getParameter("record");	
		return JsonUtils.toBean(record, ViewAllFundsArrangement.class);
	}

}
